package std::collection;

import std::Object;

public class ArrayList : List
{
	friend class ArrayListIterator;

	m_array->Object[];
	m_size->int;

	public ArrayList()
	{
		m_array = new Object[16];
		m_size=0;
	}

	public add(e->Object)
	{
		if(e==null)return;
		if(m_size < m_array.length);
		else{
			temp->Object[] = new Object[2*m_array.length];
			i->int = 0;
			while(i<m_array.length) temp[i] = m_array[i++];
			m_array = temp;
		}
		m_array[m_size++] = e;
	}

	public add(e->Object, index->int)
	{
		if(e==null)return;
		if(0<=index&&index<=m_size){
			if(m_size<m_array.length){
				i->int = m_size;
				while(index<i){
					m_array[i] = m_array[--i];
				}
				m_array[index] = e;
			}
			else{
				temp->Object[] = new Object[2*m_array.length];
				i->int = 0;
				while(i<index) {
					temp[i] = m_array[i++];
				}
				i=m_size;
				while(index<i){
					temp[i] = m_array[--i];
				}
				temp[index]=e;
				m_array = temp;
			}
			++m_size;
		}
	}

	public remove(index->int)
	{
		if(0<=index && index<m_size){
			i->int = index;
			while(i+1<m_size){
				m_array[i] = m_array[++i];
			}
			--m_size;
		}
	}

	public remove(e->Object)
	{
		if(e==null)return;
		i->int=0;
		while(i<m_size){
			if(m_array[i].equals(e)){
				while(i+1<m_size){
					m_array[i]=m_array[++i];
				}
				--m_size;
				return;
			}
			++i;
		}
	}

	public get(index->int)->Object
	{
		if(0<=index && index<m_size){
			return m_array[index];
		}
		return null;
	}

	public set(index->int, e->Object)
	{
		if(e==null)return;
		if(0<=index&&index<m_size){
			m_array[index]=e;
		}
	}

	public index(e->Object)->int
	{
		if(e==null)return -1;
		i->int=0;
		while(i<m_size){
			if(m_array[i].equals(e)){
				return i;
			}
			else ++i;
		}
		return -1;
	}

	public exist(e->Object)->boolean
	{
		if(e==null)return false;
		i->int=0;
		while(i<m_size){
			if(m_array[i++].equals(e)){
				return true;
			}
		}
		return false;
	}

	public empty()->boolean{return m_size==0;}

	public clear()
	{
		m_array = new Object[16];
		m_size = 0;
	}

	public size()->int{return m_size;}

	public iterator()->Iterator{return new ArrayListIterator(this);}

	public toArray()->Object[]
	{
		if(empty())return null;
		temp->Object[]=new Object[m_size];
		i->int=0;
		while(i<m_size){
			temp[i]=m_array[i++];
		}
		return temp;
	}
}

class ArrayListIterator : Iterator
{
	private m_vec->ArrayList;
	private m_index->int=0;
	public ArrayListIterator(vec->ArrayList){m_vec=vec;}
	public hasNext()->boolean
	{
		return m_index<m_vec.m_size;
	}
	public next()->Object
	{
		if(m_index<m_vec.m_size)return m_vec.m_array[m_index++];
		else return null;
	}
}